<?php

namespace app\api\controller;

use app\common\model\CarModel;
use app\common\model\Dept;
use app\common\model\Insure;
use app\common\model\Order;
use app\common\model\OrderBoard;
use app\common\model\OrderBoardItem;
use app\common\model\OrderLogisticsLog;
use app\common\model\OrderTrip;
use app\common\service\DeptService;
use app\common\service\OrderService;
use app\common\service\UserService;
use app\common\utils\Image;
use app\common\validate\OrderValidate;
use taoser\exception\ValidateException;
use think\facade\Db;

class OrderController
{
    
    public function vars()
    {
        $insureType = Insure::field('id,title')->select();
        return apiSuccess(data: [
            'end_dept' => DeptService::exclude(),
            'shipper_type' => Order::SHIPPER_TYPE,
            'pay_type' => Order::PAY_TYPE,
            'collection_car_type' => Order::COLLECTION_CAR_TYPE,
            'insure_type' => [
                ['id' => 0, 'title' => '请选择保价项目'],
                ...$insureType->toArray()
            ]
        ]);
    }
    
    
    /**
     * 创建订单
     * @return \support\Response
     * @throws \app\common\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function create()
    {
        $data = request()->post();
        OrderService::create($data);
        return apiSuccess('创建成功');
    }

    /**
     * 修改订单
     * @return \support\Response
     */
    public function updateOrder()
    {
        $data = request()->post();
        OrderService::updateOrder($data);
        return apiSuccess('修改成功');
    }
    
    /**
     * 详情
     * @return \support\Response
     */
    public function detail()
    {
        $id = request()->get('id', 0);
        return apiSuccess(data: OrderService::detail($id));
    }
    
    /**
     * 获取订单的当前站
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTrip()
    {
        $id = request()->get('id', 0); 
        $userInfo = UserService::get();
        $where[] = ['order_id','=',(int)$id];
        
        if($userInfo['user_type'] === 1){
            $where[] = ['dept_id','=',$userInfo['dept_id']];
        }
        
        $trip = OrderTrip::where($where)->find()->toArray();   
        $end_dept_id = Order::where('id',$trip['order_id'])->value('end_dept_id');
        $arr = [];
        
        // if($userInfo['user_type'] === 2 || (int)$end_dept_id === (int)$trip['dept_id']){
            $photos = OrderTrip::where('order_id','=',(int)$id)->column('photos'); 
            foreach ($photos as $key => $value){
                if($value){
                    $str = json_decode($value,true);
                    foreach ($str as $v2){
                        if (strpos($v2['url'], 'http://sc.dm.ccjwcm.com') !== false) {
                            $v2['url'] = str_replace('http://sc.dm.ccjwcm.com', 'http://admin.nmshicheng.com', $v2['url']);
                        }
                        $arr[] = $v2;
                    }
                }
            }
        // }

        // if(!empty($arr)){
            $trip['photos'] = $arr;
        // }
        
        return apiSuccess(data: [
            'trip' => $trip
        ]);
    }
    
    
    
    
    
    
    public function save()
    {
        $data = request()->post();
        OrderService::update($data['id'], $data['status'], $data['data']);
        return apiSuccess();
    }
    
    /**
     * 获取出了自己的部门
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDepts()
    {
        $search = request()->get('carKeyword', '');
        return apiSuccess(data: DeptService::exclude($search));
    }
    
    /**
     * 等待配板发车的车辆
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function waitboard()
    {
        $deptId = UserService::getValue('dept_id');
        $list = OrderTrip::where([
            ['dept_id', '=', $deptId],
            ['status', '=', 2]
        ])->with(['orderinfo'])->select()->each(function ($item) {
            // $item->start_dept_name = Dept::where('id', $item->start_dept_id)->value('name');
            // $item->end_dept_name = Dept::where('id', $item->end_dept_id)->value('name');
        });
        return apiSuccess(data: $list->toArray());
    }
    
    /**
     * 配板发车
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function outcar()
    {
        $data = request()->post();
        OrderService::createDeparture($data);
        return apiSuccess();
    }
    
    /**
     * 获取订单物流记录
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getLogistics()
    {
        $id = request()->get('id', 0);
        $list = OrderLogisticsLog::where('order_id', $id)->order('id asc')->select();
        return apiSuccess(data: $list->toArray());
    }
    
    /**
     * 异常订单更新
     * @return \support\Response
     * @throws \app\common\exception\ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function exceptionUpdate()
    {
        $id = request()->post('id', 0);
        $status = request()->post('status', '');
        OrderService::updateExceptionStatus($id, $status);
        return apiSuccess('修改成功');
    }
    
    
    /**
     * 创建合同
     * @return \support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createContract()
    {
        $data = request()->post();
        $orderService = new OrderService();
        $path = $orderService->createContract($data);
        return apiSuccess(data: [
            'image' => getImageUrl($path)
        ]);
    }
    
    
    /**
     * 签合同
     * @return \support\Response|void
     * @throws \think\db\exception\DbException
     */
    public function updateContract()
    {
        if (request()->method() === 'POST') {
            $post = request()->post();
            Order::where('id', $post['id'])->update([
                'contract_status' => 1,
                'status' => 1
            ]);
            return apiSuccess('签署成功');
        }
    }
    
    public function lists()
    {
        $scene = request()->post('scene', '');
        $options = request()->post('option', []);
        $list = OrderService::getLists($scene, $options);
        return apiSuccess(data: $list->items());
    }
    
    public function tabslist()
    {
        $list = [
			[ "title"=>'查询运单', "list"=>[], "state"=>'noload', "status"=>"", "identity"=>"" ],
			[ "title"=>'拍照验车', "list"=>[], "state"=>'noload', "status"=>0, "identity"=>'start' ],
			[ "title"=>'提回待发', "list"=>[], "state"=>'noload', "status"=>1, "identity"=>'start' ],
			[ "title"=>'入库可发', "list"=>[], "state"=>'noload', "status"=>2, "identity"=>'start' ],
			[ "title"=>'中转接车', "list"=>[], "state"=>'noload', "status"=>0, "identity"=>'center' ],
			[ "title"=>'中转待发', "list"=>[], "state"=>'noload', "status"=>1, "identity"=>'center' ],
			[ "title"=>'中转可发', "list"=>[], "state"=>'noload', "status"=>2, "identity"=>'center' ],
			[ "title"=>'终到接车', "list"=>[], "state"=>'noload', "status"=>0, "identity"=>'end' ],
			[ "title"=>'终点无站', "list"=>[], "state"=>'noload', "status"=>0, "identity"=>'noEnd' ],
			[ "title"=>'已完结', "list"=>[], "state"=>'noload', "status"=>4, "identity"=>'' ]
		];
		foreach ($list as $key=>$val){
		    if($val['title']!="已完结"&&$val['title']!="查询运单"){
		        $count = 0;
		        $options = ["status"=>$val['status'],"identity"=>$val['identity'],"keyword"=>""];
		        $count = OrderService::getLists('dept.list', $options, false, true);
		        if($count){
		            $list[$key]['badge'] = ["text"=>$count, "boxStyle"=>'top:0;right:0;', "textStyle"=>'fontSize:18rpx'];
		        }
		    }
		}
        return apiSuccess(data: $list);
    }
    
    
    public function triplist()
    {
        $startTime = request()->get('start_time',date('Y-m-d'));
        $endTime = request()->get('end_time',date('Y-m-d'));
        $typesOf = (int)request()->get('type',0);
        $deptId = UserService::getValue('dept_id');
        $where = []; 
        if($typesOf === 0){
            $where[] = ['start_dept_id', '=', $deptId];
            $where[] = ['dept_id', '=', $deptId];
        }
        if($typesOf === 1){
            $where[] = ['dept_id', '=', $deptId];
            $where[] = ['dept_id', 'exp', Db::raw('<> start_dept_id')];
        }
        if($typesOf === 2){
            // $where[] = ['next_dept_id', '=', $deptId];
            $where[] = ['end_dept_id', '=', $deptId];
        } 
        $where[] = ['create_time', 'between', [$startTime, $endTime . ' 23:59:59']];
        
        $list = OrderBoardItem::with(['orderinfo','board','start_dept','end_dept'])->where($where)->group("order_id")->order('id desc')->paginate();
        
        return apiSuccess(data: ['list'=>$list->items(),'total'=>$list->total()]);
    }
    
    public function checkout()
    {
        $id = request()->post('id', 0);
        $deptId = UserService::getValue('dept_id');
        $where = [
            ['id', '=', $id],
            ['dept_id', '=', $deptId]
        ];
        OrderBoardItem::where($where)->update([
            'status' => 1
        ]);
        return apiSuccess('修改成功');
    }
    
    public function statistics()
    {
        $deptId = UserService::getValue('dept_id');
        $where[] = ['create_time', 'between', [date('Y-m-01'), date('Y-m-d 23:59:59')]];
        $startStatistics = OrderBoardItem::where('start_dept_id', $deptId)
            ->where('dept_id', $deptId)
            ->where($where)
            ->field('count(DISTINCT order_id) as number,sum(total_price) as total_price')
            ->find()->toArray();
        $centerStatistics = OrderBoardItem::where('dept_id', $deptId)
            ->where('start_dept_id', 'not in', $deptId)
            ->where('end_dept_id', 'not in', $deptId)
            ->where($where)
            ->field('count(DISTINCT order_id) as number,sum(total_price) as total_price')
            ->find()->toArray();
        $endStatistics = OrderBoardItem::where('end_dept_id', $deptId)
            ->where($where)
            ->field('count(DISTINCT order_id) as number,sum(total_price) as total_price')
            ->find()->toArray();
        return apiSuccess(data: [
            'start' => $startStatistics,
            'center' => $centerStatistics,
            'end' => $endStatistics,
            'tel' => '4000080612'
        ]);
    }
    
    public function driverHistory(){
        $deptId = UserService::getValue('dept_id');
        return apiSuccess(data:OrderBoard::where('dept_id',$deptId)->where('driver_mobile','<>','')->group('driver_mobile')->field('driver_mobile,driver_name,license')->select()->toArray());
    }
    
    public function companyHistory(){
        $deptId = UserService::getValue('dept_id');
        return apiSuccess(data:OrderBoard::where('dept_id',$deptId)->where('company_mobile','<>','')->group('company_mobile')->field('company_mobile,company_name,company_nickname')->select()->toArray());
    }
    
    public function shipperHistory(){
        $deptId = UserService::getValue('dept_id');
        return apiSuccess(data:Order::where('dept_id',$deptId)->where('shipper_mobile','<>','')->group('shipper_mobile')->field('shipper_mobile as mobile,shipper_name as name')->select()->toArray());
    }
    
    public function acceptHistory(){
        $deptId = UserService::getValue('dept_id');
        return apiSuccess(data:Order::where('dept_id',$deptId)->where('accept_mobile','<>','')->group('accept_mobile')->field('accept_mobile as mobile,accept_name as name')->select()->toArray());
    }
    
    public function cancel(){
        $id = request()->get('id',0);
        if(OrderService::cancelOrder($id)){
            return apiSuccess('删除成功');
        }else{
            return apiError('删除失败');
        }
    }
    
    public function endpush(){
        $data = request()->post();
        OrderService::endpush($data);
        return apiSuccess('发车成功');
    }
    
    public function getCarModel() {
        $type = request()->get('type', 1);
        $data = [];
        if ($type == 1) {
            $data = CarModel::where(["status"=>1])->field("id,name")->order("orders asc")->select()->toArray();
        } else {
            $class = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
            for ($i=0; $i<count($class); $i++) {
                $data[] = [
                    "name" => $class[$i],
                    "list" => self::getCarModelType($data[$i])
                ];
            }
        }
        return apiSuccess('车辆品牌', $data);
    }

    public static function getCarModelType($firstletter) {
        return CarModel::where(["status"=>1, "firstletter"=>$firstletter])->order("orders asc")->select()->toArray();
    }
    
    
}